/*
 * Copyright (c) 2023 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include "i_i2c.h"
#include <mc/log.h>

namespace dev {

// I2C速度映射表
static uint32_t i2c_speed_map[] = {
    100, // 0 -> 100K
    400, // 1 -> 400K
    3400 // 2 -> 3400K
};

uint32_t Interface_I2c::get_i2c_speed(uint32_t speed) {
    // 确保speed在有效范围内，避免数组越界
    constexpr size_t speed_map_size = sizeof(i2c_speed_map) / sizeof(i2c_speed_map[0]);
    if (speed >= speed_map_size) {
        return speed;
    }
    return i2c_speed_map[speed];
}

void Interface_I2c::from_variant(mc::mutable_dict& csr_object) {
    try {
        // 从字典中提取各个属性值并设置到对象中
        if (csr_object.contains("Id")) {
            this->Id = csr_object["Id"].as<uint8_t>();
        }

        if (csr_object.contains("Speed")) {
            this->Speed = this->get_i2c_speed(csr_object["Speed"].as<uint32_t>());
        }

        if (csr_object.contains("Mode")) {
            this->Mode = csr_object["Mode"].as<uint8_t>();
        }

        if (csr_object.contains("SlaveAddr")) {
            this->SlaveAddr = csr_object["SlaveAddr"].as<uint8_t>();
        }

        if (csr_object.contains("UseSmbus")) {
            this->UseSmbus = csr_object["UseSmbus"].as<bool>();
        }
    } catch (const std::exception& e) {
        elog("I2C configuration loading failed: ${error}", ("error", e.what()));
        throw;
    }
}

} // namespace dev

MC_REFLECT(dev::Interface_I2c)
